package com.cndw.kungfu.model.scene;

import java.util.concurrent.atomic.AtomicIntegerArray;

import com.cndw.kungfu.config.ConstantsConfig;

public class SubLineCore {
	/**
	 * 全线在线人数
	 */
	private static AtomicIntegerArray mainSubLineUsers;

	private AtomicIntegerArray subLineUsers;
	/**
	 * 多少人开始换线
	 */
	private static int overFlowNum = 0;

	public SubLineCore(int sublineNum) {

		subLineUsers = new AtomicIntegerArray(sublineNum + 1);
		if (mainSubLineUsers == null) {
			synchronized (SubLineCore.class) {
				if (mainSubLineUsers == null) {
					mainSubLineUsers = new AtomicIntegerArray(sublineNum + 1);
				}
			}
		}
		overFlowNum = overFlowNum <= 0 ? ConstantsConfig.getSysSubLineOverflow() : overFlowNum;
	}

	public int makeSubLine() {

		int subLine = 0;
		int minLine = 1;
		for (int i = 1; i < subLineUsers.length(); i++) {
			if (subLineUsers.get(i) < overFlowNum) {
				subLine = i;
				break;
			}
			if (minLine != i && subLineUsers.get(minLine) > subLineUsers.get(i)) {
				minLine = i;
			}
		}
		if (subLine == 0) {
			subLine = minLine;
		}
		enterSubLine(subLine);
		return subLine;
	}

	public void enterSubLine(int subLine) {
		subLineUsers.incrementAndGet(subLine);
		mainSubLineUsers.incrementAndGet(subLine);
	}

	public void exitSubLine(int subLine) {
		subLineUsers.decrementAndGet(subLine);
		mainSubLineUsers.decrementAndGet(subLine);
	}

	public int[] getSubLineNums() {
		int[] subLineNums = new int[subLineUsers.length()];
		for (int i = 0; i < subLineNums.length; i++) {
			subLineNums[i] = subLineUsers.get(i);

		}
		return subLineNums;
	}

	public static int[] getMainSubLineNums() {
		int[] subLineNums = new int[mainSubLineUsers.length()];
		for (int i = 0; i < subLineNums.length; i++) {
			subLineNums[i] = mainSubLineUsers.get(i);
		}
		// LogBase.loger.debug(mainSubLineUsers.toString());
		return subLineNums;
	}

	public static int getOverFlowNum() {
		return overFlowNum;
	}

	public static void setOverFlowNum(int overFlowNum) {
		SubLineCore.overFlowNum = overFlowNum;
	}

}
